package data

import (
	"commerce/common"
	"commerce/model"
	"commerce/req"
	"database/sql"
	"fmt"
	"strings"
	"time"
)

func GetMemberByWxInfo(openId string) (*model.Member, error) {

	sqlTpl := "select id, name, nick_name, phone, open_id, session_key FROM member where open_id = ?"

	stmt, err := common.DB.Prepare(sqlTpl)
	if err != nil {
		return nil, err
	}
	defer stmt.Close()

	var m model.Member
	if err = stmt.QueryRow(openId).Scan(&m.Id, &m.Name, &m.NickName, &m.Phone, &m.OpenId, &m.SessionKey); err != nil {
		if err == sql.ErrNoRows {
			return nil, nil
		}
		return nil, err
	}
	return &m, nil
}

func GetMemberById(id int) (*model.Member, error) {

	sqlTpl := "select id, phone, name, nick_name, avatar, open_id, session_key, birth, gender, status, country, province, city, created_time, updated_time FROM member where id = ?"

	stmt, err := common.DB.Prepare(sqlTpl)
	if err != nil {
		return nil, err
	}
	defer stmt.Close()

	var m model.Member
	if err = stmt.QueryRow(id).Scan(&m.Id, &m.Phone, &m.Name, &m.NickName, &m.Avatar, &m.OpenId, &m.SessionKey, &m.BirthStr, &m.Gender, &m.Status,
		&m.Country, &m.Province, &m.City, &m.CreatedTimeStr, &m.UpdatedTimeStr); err != nil {
		return nil, err
	}
	m.GenderStr = translateGender(m.Gender)

	return &m, nil
}

func translateGender(gender int8) string {
	switch gender {
	case 0:
		return "未知"
	case 1:
		return "男"
	case 2:
		return "女"
	}
	return "未知"
}

func AddMember(m model.Member) (int, error) {

	sqlTpl := "insert into member(nick_name, avatar, gender, open_id, session_key, status, country, province, city, created_time, updated_time) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?,?,?)"
	result, err := common.DB.Exec(sqlTpl, m.NickName, m.Avatar, m.Gender, m.OpenId, m.SessionKey, m.Status, m.Country, m.Province, m.City, time.Now().Add(8*time.Hour), time.Now().Add(8*time.Hour))

	if err != nil {
		return 0, err
	}
	id, err := result.LastInsertId()

	if err != nil {
		return 0, fmt.Errorf("save member insert id err: %v", err)
	}
	return int(id), nil
}

func UpdateMemberById(memberId int, info req.UserInfo) error {

	sqlTpl := "update member set nick_name=?, avatar=?, gender = ?, country=?, province=?, city=?, updated_time = ? WHERE id = ?"

	stmt, err := common.DB.Prepare(sqlTpl)
	if err != nil {
		return err
	}
	defer stmt.Close()

	result, err := stmt.Exec(info.NickName, info.AvatarUrl, info.Gender, info.Country, info.Province, info.City, time.Now().Add(8*time.Hour), memberId)
	if err != nil {
		return fmt.Errorf("update member info err:%v", err.Error())
	}
	_, err = result.RowsAffected()
	return err
}

func PageUser(pageNo, pageSize int, name string) (*common.Page, error) {

	whereSql := composeUserSearchQuerySql(name)

	row := common.DB.QueryRow("select count(*) FROM member" + whereSql)
	var totalRecords int
	if err := row.Scan(&totalRecords); err != nil {
		return nil, err
	}
	stmt, err := common.DB.Prepare("select id, phone, name, nick_name, avatar, birth, gender, status, country, province, city, created_time, updated_time FROM member" + whereSql + " LIMIT ?, ?")
	if err != nil {
		return nil, err
	}
	defer stmt.Close()

	rows, err := stmt.Query((pageNo-1)*pageSize, pageSize)
	if err != nil {
		return nil, err
	}
	defer rows.Close()

	var ms []model.Member
	for rows.Next() {
		m := model.Member{}
		if err := rows.Scan(&m.Id, &m.Phone, &m.Name, &m.NickName, &m.Avatar, &m.BirthStr, &m.Gender, &m.Status,
			&m.Country, &m.Province, &m.City, &m.CreatedTimeStr, &m.UpdatedTimeStr); err != nil {
			return nil, fmt.Errorf("会员用户分页数据有误:%s", err.Error())
		}
		m.City = fmt.Sprintf("%s/%s/%s", m.Country, m.Province, m.City)
		m.GenderStr = translateGender(m.Gender)
		ms = append(ms, m)
	}
	return common.NewPage(ms, pageNo, pageSize, totalRecords), nil
}

func UpdateMemberStatus(memberId int, status int8) error {

	sqlTpl := "update member set status = ?, updated_time = ? WHERE id = ?"

	stmt, err := common.DB.Prepare(sqlTpl)
	if err != nil {
		return err
	}
	defer stmt.Close()

	result, err := stmt.Exec(status, time.Now().Add(8*time.Hour), memberId)
	if err != nil {
		return fmt.Errorf("update member status err:%v", err.Error())
	}
	_, err = result.RowsAffected()
	return err
}

func UpdateMemberEmail(memberId int, email string) error {

	stmt, err := common.DB.Prepare("update member set email = ?, updated_time = ? WHERE id = ?")
	if err != nil {
		return err
	}
	defer stmt.Close()

	result, err := stmt.Exec(email, time.Now().Add(8*time.Hour), memberId)
	if err != nil {
		return fmt.Errorf("update member email info err:%v", err.Error())
	}
	_, err = result.RowsAffected()
	return err
}

func composeUserSearchQuerySql(name string) string {

	// 没有条件查询
	if len(name) == 0 {
		return ""
	}
	sb := strings.Builder{}
	sb.WriteString(" WHERE nick_name like '" + strings.TrimSpace(name) + "%' ")

	return sb.String()
}
